import sls_coordinationConvert
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QPushButton, QLineEdit, QListWidget, 
                            QLabel, QMessageBox,QDialog)
from PyQt6.QtGui import QBrush,QColor
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QDialog
import sys
from  sls_ugvNormalMissions.sls_ugvMissionsCarFollowPoint import Ui_MissionsCarFollowPoint

class ngc_NormalMissions(QWidget):
    def __init__(self,parent,index:int=-1):
        super().__init__()
        self.add_index = index      
        self.parent = parent
        self.id = parent.id
        self.mirror_agent = parent.mirror_agent
        self.notifyClass = parent.notifyClass
    
    def add_mission(self,takeoffDict):
        if self.add_index == -1:
            self.mirror_agent.append_mission_to_schedule(self.id,takeoffDict)
        else:
            self.mirror_agent.add_mission_to_schedule(self.id,takeoffDict,self.add_index)    
        #更新列表
        self.mirror_agent.request_scheduleUpdate_missions_list(self.id)
    
    def close_window(self):
        self.close()



class ngc_MissionsCarFollowPoint(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.setWindowFlags(Qt.WindowType.WindowStaysOnTopHint)
        self.ui = Ui_MissionsCarFollowPoint()
        self.ui.setupUi(self)
        self.setWindowTitle(f"{self.id} 纯跟踪")
        self.ui.pushButton.clicked.connect(self.pushButton_clicked)
        self.notifyClass.add_notify_Cordinate(self.on_click_point)

    def on_click_point(self,latitude,longitude):
        self.parent.parent.add_marker(latitude,longitude,f'{self.id}temppoint')
        self.longitude,self.latitude = longitude,latitude
        #在界面显示显示WGS84坐标
        self.ui.positionLabel.setText(f"WGS84坐标，经度：{self.longitude} 纬度：{self.latitude}")


    def pushButton_clicked(self):
        yaw = self.ui.yawSpinBox.value()
        #删点
        self.parent.parent.del_marker(f'{self.id}temppoint')
        #组合并发送
        CarFollowPointDict = {
            "missionsType": "MissionsCarFollowPoint",
            "datasets":{
               "GNSS_position":[self.latitude,self.longitude,0.0],
                "vehicle_yaw": yaw
            }
        }
        self.add_mission(CarFollowPointDict)
        self.close_window()

    def closeEvent(self, event):
        self.notifyClass.remove_notify_Cordinate(self.on_click_point)
from PyQt6 import QtCore, QtGui, QtWidgets
import polyline
class ngc_MissionsSTM32Serialpub(ngc_NormalMissions):
    def __init__(self,parent,index:int=-1):
        super().__init__(parent,index)
        self.setWindowTitle(f"{self.id} pub path to stm32")
        self.drag_label = QLabel("请将txt文件拖入此处")
        self.drag_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.drag_label.setStyleSheet("""
            background-color: white;
            color: black;
            font-size: 16px;
            border: 1px solid #ccc;
            padding: 30px;
        """)
        self.lon_lan_temp = []
        show_button = QPushButton("显示路径")
        enter_button = QPushButton("确认")
        cancel_button = QPushButton("取消")

        hlayout = QHBoxLayout()
        hlayout.addStretch()
        hlayout.addWidget(show_button)
        hlayout.addWidget(enter_button)
        hlayout.addWidget(cancel_button)

        vlayout = QVBoxLayout()
        vlayout.addWidget(self.drag_label)
        vlayout.addLayout(hlayout)
        self.setLayout(vlayout)

        self.setAcceptDrops(True)

        show_button.clicked.connect(self.show_button_clicked)
        enter_button.clicked.connect(self.enter_button_clicked)
        cancel_button.clicked.connect(self.cancel_button_clicked)

        self.lat_lon_encoded = None
    def dragEnterEvent(self, event:QtGui.QDropEvent):
        if event.mimeData().hasUrls():  # 检查是否是文件
            event.acceptProposedAction()  # 接受拖拽
            self.drag_label.setText(f"请松手传入")
    def dragLeaveEvent(self, event: QtGui.QDropEvent):
        # 当拖拽离开窗口时恢复原始文本
        self.drag_label.setText("请将txt文件拖入此处")
        event.accept()
    def dropEvent(self, event:QtGui.QDropEvent):
        self.lon_lat_temp = []
        self.lat_lon_temp = []
        files = event.mimeData().urls()  # 获取所有文件路径
        for url in files:
            file_path = url.toLocalFile()  # 转换为本地文件路径
            self.drag_label.setText(f"拖入文件: {file_path}")
            try:
                with open(file_path,"r",encoding="utf-8") as f:
                    for line in f:
                        line = line.strip()
                        line_list = line.split(", ")
                        self.lon_lat_temp.append([float(line_list[0]), float(line_list[1])])
                        self.lat_lon_temp.append((float(line_list[1]), float(line_list[0])))
                self.lat_lon_encoded = polyline.encode(self.lat_lon_temp,precision=8)
                # print("Encoded Polyline:", sys.getsizeof(self.lat_lon_encoded)/sys.getsizeof(self.lat_lon_temp))
                # print(sys.getsizeof(self.lat_lon_temp))
            except Exception as e:
                self.drag_label.setText(f"\n读取失败，请重试\n错误类型：{str(e)},")
            except:
                self.drag_label.setText(f"\n未知错误")

    def show_button_clicked(self):
        self.parent.parent.add_polyline(self.lon_lat_temp,"#0E9B91","load_path",2,1)
    def enter_button_clicked(self):
        if self.lat_lon_encoded is not None:
            self.parent.parent.del_polyline("load_path")
            MissionsSTM32SerialpubDict = {
                "missionsType": "MissionsSTM32Serialpub",
                "datasets":{
                "lat_lon_encoded":self.lat_lon_encoded,
                }
            }
            self.add_mission(MissionsSTM32SerialpubDict)
            self.close()
        else:
            QMessageBox.warning(
                self,
                "未上传文件",
                "请上传文件或点击“取消”退出。",
                QMessageBox.StandardButton.Ok
            )
    def cancel_button_clicked(self):
        self.parent.parent.del_polyline("load_path")
        self.close()


missions_table={
                "MissionsCarFollowPoint":ngc_MissionsCarFollowPoint,
                "MissionsSTM32Serialpub":ngc_MissionsSTM32Serialpub
                }
